package com.yuji.aacar.core.cores.utils;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * <li>Package:com.ttp.core.cores.utils</li>
 * <li>Author: lining</li>
 * <li>Date: 2017/2/20</li>
 * <li>Description: 文件处理类</li>
 *  <li>boss,dealer,customer,checker 目前只有这四个AppName</li>
 */
public class CoreFileUtil {

    public static String TAG = "文件处理";
    public static String BOSS_APP = "boss";
    public static String DEALER_APP = "dealer";
    public static String CUSTOMER_APP = "customer";
    public static String CHECKER_APP = "checker";

    /******全局保存总目录*******/
    public static String LOG_TOTAL_NAME = "Ttpai";

    /******数据库最终路径*******/
    public static String DB_PATH_NAME;

    /******日志类型*******/
    public static int LOG_FOR_CRASH = 0; //崩溃日志
    public static int LOG_FOR_SERVER = 1;//服务器异常日志

    /******崩溃日志的存储名称*******/
    public static File LOG_FILE_FOR_CRASH_REPORT; //最终崩溃日志log日志存储的位置
    public static String LOG_PATH_FOR_CRASH_REPORT; //最终崩溃日志log日志存储的位置
    public static String BossLog = "boss.log";
    public static String CheckerLog = "checker.log";
    public static String ConsumerLog = "consumer.log";
    public static String DealerLog = "dealer.log";
    public static String ServerLog = "server.log";

    /****** 默认的存储类型为sd卡  0 *******/
    public  static final int SDCARD_TYPE = 0; // 当前的日志记录类型为存储在SD卡下面
    public  static final int MEMORY_TYPE = 1; // 当前的日志记录类型为存储在内存中
    public  static int CURR_LOG_TYPE = SDCARD_TYPE; // 当前的日志记录类型

    public  static String LOG_PATH_MEMORY_DIR; // 日志文件在内存中的路径(日志文件在安装目录中的路径)
    public  static String LOG_PATH_SDCARD_DIR; // 日志文件在sdcard中的路径

    public  static String crashLogName = "Ttpai.log"; // 崩溃日志名
//    public  String CURR_INSTALL_LOG_NAME;//当前安装log名称

    /****** 服务器类型错误日志 *******/
    public static File LOG_FILE_FOR_SERVER_REPORT; //服务器类型的日志
    public static String LOG_PATH_FOR_SERVER_REPORT; //服务器错误日志
    public  static String LOG_PATH_MEMORY_DIR_FOR_SERVER; // 日志文件在内存中的路径(日志文件在安装目录中的路径)
    public  static String LOG_PATH_SDCARD_DIR_FOR_SERVER; // 日志文件在sdcard中的路径


    /******数据库文件的存储生成*******/
    public static String DB_PATH; //本地数据库存储路径
    public static File DB_FILE; //本地数据库

    private static SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static OutputStreamWriter writer;

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            //			int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    //					bytesum += byteread; // 字节数 文件大小
                    //					System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                fs.close();
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 复制整个文件夹内容
     *
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath
                            + "/" + (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }

    private static final String imgSavePath = "/Lp/save/";

    /**
     * 图片命名
     *
     * @return
     */
    public static String getSaveFilePath() {
        File outputDri = new File(
                Environment.getExternalStorageDirectory(),
                imgSavePath);
        if (!outputDri.exists()) {
            if (!outputDri.mkdirs()) {
                return null;
            }
        }

        String timeTmp = new SimpleDateFormat("yyyy_MMdd_HHmmss")
                .format(new Date());
        File outputUri = new File(outputDri.getPath() + File.separator
                + "avatar_" + timeTmp + ".jpg");

        LogUtil.e("要保存的图片命名", outputUri.getPath());
        return outputUri.getPath();
    }

    /**
     * 头像上传的图片路径命名
     *
     * @return
     */
    public static String getUploadAvatarPath() {
        File outputDri = new File(
                Environment.getExternalStorageDirectory(),
                CoreSdCardUtil.getUploadAvatar());
        if (!outputDri.exists()) {
            if (!outputDri.mkdirs()) {
                return null;
            }
        }

        //		String timeTmp = new SimpleDateFormat("yyyy_MMdd_HHmmss")
        //				.format(new Date());
        File outputUri = new File(outputDri.getPath() + File.separator
                + "avatar" + ".jpg");

        LogUtil.e("头像上传的图片路径命名", outputUri.getPath());
        return outputUri.getPath();
    }


    /**
     * Delete file(include not empty directory)
     *
     * @param file
     */
    public static boolean deleteFile(File file) {
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File file2 : files) {
                    deleteFile(file2);
                }
            }
            return file.delete();
        }
        return false;
    }

    /**
     * 获取数据库路径
     *
     * @param context
     * @return 数据库所在的文件目录
     */
    public static String getDataBasePath(Context context) {
        String path = context.getDatabasePath("dbFilesPath").getAbsolutePath();
        int index = path.lastIndexOf('/');
        String dataBasePath = path.substring(0, index);
        return dataBasePath;
    }


    /**
     * 消息写入文件中
     *
     * @param fileLog
     * @param msg
     */
    public static void writeFileToPath(File fileLog, String msg) {
        if (null != fileLog) {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    try {
                        writer = new OutputStreamWriter(new FileOutputStream(fileLog, true),"UTF-8");// 字节流变为字符流
                        Date time = new Date();
                        writer.write(myLogSdf.format(time) + " : " + msg);
                        writer.write("\n");
                        writer.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }


    /**
     * 创建日志目录
     */
    public static File getDBDirAccordingAppName(Context context, String appName, String fileName) {

        crashLogName = fileName;
        LOG_PATH_MEMORY_DIR = context.getFilesDir().getAbsolutePath() + File.separator  + LOG_TOTAL_NAME + File.separator + appName + File.separator + fileName;
        LOG_PATH_SDCARD_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + LOG_TOTAL_NAME + File.separator + appName+ File.separator + fileName;

        CoreFileUtil.CURR_LOG_TYPE = getCurrLogType();
        LogUtil.e(TAG, "LOG_PATH_MEMORY_DIR  :" + LOG_PATH_MEMORY_DIR);
        LogUtil.e(TAG, "LOG_PATH_SDCARD_DIR  :" + LOG_PATH_SDCARD_DIR);
        LogUtil.e(TAG, "CURR_LOG_TYPE  :" + CURR_LOG_TYPE);
        LOG_FILE_FOR_CRASH_REPORT = CoreFileUtil.createLogDir(LOG_FOR_CRASH);
        //        CoreFileUtil.logFilePath = fileLog;
        LogUtil.e(TAG, "crash log path  :"+ LOG_PATH_FOR_CRASH_REPORT);

        return LOG_FILE_FOR_CRASH_REPORT;
    }


    public static File createAllLogDirAccordingAppName(Context context, String appName, String fileName) {
        File crashFile = createLogDirAccordingAppName(context,appName, fileName);
        createServerLogDirAccordingAppName(context,appName, fileName);
        return crashFile;
    }
    /**
     * 创建崩溃日志目录
     */
    public static File createLogDirAccordingAppName(Context context, String appName, String fileName) {
        crashLogName = fileName;
        LOG_PATH_MEMORY_DIR = context.getFilesDir().getAbsolutePath() + File.separator  + LOG_TOTAL_NAME + File.separator + appName + File.separator + fileName;
        LOG_PATH_SDCARD_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + LOG_TOTAL_NAME + File.separator + appName+ File.separator + fileName;

        CoreFileUtil.CURR_LOG_TYPE = getCurrLogType();
        LogUtil.e(TAG, "LOG_PATH_MEMORY_DIR  :" + LOG_PATH_MEMORY_DIR);
        LogUtil.e(TAG, "LOG_PATH_SDCARD_DIR  :" + LOG_PATH_SDCARD_DIR);
        LogUtil.e(TAG, "CURR_LOG_TYPE  :" + CURR_LOG_TYPE);
        LOG_FILE_FOR_CRASH_REPORT = CoreFileUtil.createLogDir(LOG_FOR_CRASH);
//        CoreFileUtil.logFilePath = fileLog;
        LogUtil.e(TAG, "crash log path  :"+ LOG_PATH_FOR_CRASH_REPORT);
        return LOG_FILE_FOR_CRASH_REPORT;
    }

    /**
     * 创建服务器异常日志目录
     */
    public static File createServerLogDirAccordingAppName(Context context, String appName, String fileName) {
        LOG_PATH_MEMORY_DIR_FOR_SERVER = context.getFilesDir().getAbsolutePath() + File.separator  + LOG_TOTAL_NAME + File.separator + appName + File.separator + fileName;
        LOG_PATH_SDCARD_DIR_FOR_SERVER = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + LOG_TOTAL_NAME + File.separator + appName+ File.separator + fileName;

        LOG_FILE_FOR_SERVER_REPORT = CoreFileUtil.createLogDir(LOG_FOR_SERVER);
        //        CoreFileUtil.logFilePath = fileLog;
        LogUtil.e(TAG, "server log path  :"+ LOG_FILE_FOR_SERVER_REPORT);
        return LOG_FILE_FOR_CRASH_REPORT;
    }

    /**
     * 创建日志目录
     */
    public static File createLogDir(int type) {
        String filename = "";
        if (type == LOG_FOR_CRASH){
            filename = CURR_LOG_TYPE == MEMORY_TYPE ? LOG_PATH_MEMORY_DIR : LOG_PATH_SDCARD_DIR;
        } else if (type == LOG_FOR_SERVER){
            filename = CURR_LOG_TYPE == MEMORY_TYPE ? LOG_PATH_MEMORY_DIR_FOR_SERVER : LOG_PATH_SDCARD_DIR_FOR_SERVER;
        }

        //		System.out.println("Log本地日志地址---"+filename);
        //		Log.e(TAG, "filename: "+filename);
        File file = new File(filename);
        boolean mkOk;
        if (!file.isDirectory()) {
            mkOk = file.mkdirs();
            if (!mkOk) {
                mkOk = file.mkdirs();
            }
        }
        File fileLog = null;
        if (type == LOG_FOR_CRASH){
            LOG_PATH_FOR_CRASH_REPORT = filename + File.separator + crashLogName;
            fileLog = new File(LOG_PATH_FOR_CRASH_REPORT);
        } else if (type == LOG_FOR_SERVER){
            LOG_PATH_FOR_SERVER_REPORT = filename + File.separator + ServerLog;
            fileLog = new File(LOG_PATH_FOR_SERVER_REPORT);
        }

//        File fileLog = new File(LOG_PATH_FOR_CRASH_REPORT);
        Log.e(TAG, "CURR_INSTALL_LOG_NAME  :" + LOG_PATH_FOR_CRASH_REPORT);
        Log.e(TAG, "fileLog  :" + fileLog);
        return fileLog;
    }

    /**
     * 创建目录
     */
    public static File createDir(String filePath) {
        String filename = CURR_LOG_TYPE == MEMORY_TYPE ? LOG_PATH_MEMORY_DIR : LOG_PATH_SDCARD_DIR;
        //		System.out.println("Log本地日志地址---"+filename);
        //		Log.e(TAG, "filename: "+filename);
        File file = new File(filename);
        boolean mkOk;
        if (!file.isDirectory()) {
            mkOk = file.mkdirs();
            if (!mkOk) {
                mkOk = file.mkdirs();
            }
        }
        LOG_PATH_FOR_CRASH_REPORT = filename + File.separator + crashLogName;
        File fileLog = new File(LOG_PATH_FOR_CRASH_REPORT);
        Log.e(TAG, "CURR_INSTALL_LOG_NAME  :" + LOG_PATH_FOR_CRASH_REPORT);
        Log.e(TAG, "fileLog  :" + fileLog);
        return fileLog;
    }

    public static void delCrashLogFile() {// 删除日志文件
//        String needDelFiel = logfile.format(getDateBefore());
//        File file = new File(logFilePath);
        if (null != LOG_FILE_FOR_CRASH_REPORT){
            if (LOG_FILE_FOR_CRASH_REPORT.exists()) {
                LOG_FILE_FOR_CRASH_REPORT.delete();
                LogUtil.e("--文件删除掉了--",LOG_FILE_FOR_CRASH_REPORT.getName());
                LogUtil.e("--文件删除掉了--",LOG_FILE_FOR_CRASH_REPORT.getPath());
            }
        }

    }

    /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    public static String readFileByLines(File file) {
//        File file = new File(fileName);
        BufferedReader reader = null;
        StringBuffer sb = new StringBuffer();
        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
//            reader = new BufferedReader(new FileReader(file));
            reader = new BufferedReader(isr);
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                LogUtil.e("crash file", "line " + line + ": " + tempString);
                System.out.println("line " + line + ": " + tempString);
                sb.append(tempString).append("\r\n");
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return sb.toString();
    }

    /**
     * 获取当前应存储在内存中还是存储在SDCard中
     *
     * @return
     */
    public static int getCurrLogType() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)) {
            Log.e(TAG, "MEMORY_TYPE");
            return MEMORY_TYPE;
        } else {
            Log.e(TAG, "SDCARD_TYPE");
            return SDCARD_TYPE;
        }
    }

    public static String getSDPath() {
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            return Environment.getExternalStorageDirectory().toString();
        } else {
            return "";
        }
    }

    /**
     * 创建数据库文件
     * @param userId
     * @param dbName
     * @return
     */
    public static File createDBPath(String userId, String dbName) {
        String dbDir = CoreFileUtil.getDBPath();
        if (TextUtils.isEmpty(dbDir)) {
            Log.e("SD卡管理：", "SD卡不存在，请加载SD卡");
            return null;
        }

        File baseFile = new File(dbDir);
        // 目录不存在则自动创建目录
        if (!baseFile.exists()) {
            baseFile.mkdirs();
        }
        StringBuffer buffer = new StringBuffer();
        buffer.append(baseFile.getPath());
        buffer.append(File.separator);
        buffer.append(userId);
        dbDir = buffer.toString();// 数据库所在目录
        buffer.append(File.separator);
        //        buffer.append(dbName+"_"+currentUserId);
        buffer.append(dbName);
        String dbPath = buffer.toString();// 数据库路径
        DB_PATH_NAME = dbPath;
        // 判断目录是否存在，不存在则创建该目录
        File dirFile = new File(dbDir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        LogUtil.e("文件夹是否创建：", dirFile.exists() + "");

        // 数据库文件是否创建成功
        boolean isFileCreateSuccess = false;
        //        // 判断文件是否存在，不存在则创建该文件
        File dbFile = new File(dbPath);
        LogUtil.e("数据库保存的目录全路径为：", dbPath);
        try {
            dbFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!dbFile.exists()) {
            try {
                isFileCreateSuccess = dbFile.createNewFile();// 创建文件
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            isFileCreateSuccess = true;
        }

        // 返回数据库文件对象
        if (isFileCreateSuccess){
            DB_PATH = dbPath;
            DB_FILE = dbFile;
            return dbFile;
        }  else {
            DB_PATH = null;
            DB_FILE = null;
            return null;
        }

    }

    public static String getDBPath() {
        String sdCardPath = getSDPath();
        if (TextUtils.isEmpty(sdCardPath)) {
            return "";
        } else {
            return sdCardPath + File.separator + LOG_TOTAL_NAME ;
        }
    }

    /**
     * 判断数据库文件是否存在
     * @return
     */
    public static boolean isDBFileExist() {
        if (TextUtils.isEmpty(DB_PATH_NAME)) {
            return false;
        } else {
            File dbFile = new File(DB_PATH_NAME);
            if (dbFile.exists()){
                return true;
            }
        }
        return false;
    }

//    public static String checkLogSize() {
//        if (LOG_PATH_FOR_CRASH_REPORT != null && !"".equals(CURR_INSTALL_LOG_NAME)) {
//            File file = new File(CURR_INSTALL_LOG_NAME);
//            if (!file.exists()) {
//                return null;
//            }
//            //			LogFactory.e(TAG, "checkLog() ==> The size of the log is too big?");
//
//            // [读取日志文件]
//            FileInputStream in = null;
//            byte[] buffer = null;
//            try {
//                in = new FileInputStream(file);
//                int totalLen = in.available();
//                buffer = new byte[totalLen];
//                Log.e(TAG, "CustomExceptionHandler totalLen :" + totalLen);
//                while (in.read(buffer) != -1) {
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                Log.e(TAG, e.getMessage(), e);
//                return null;
//            } finally {
//                try {
//                    if (in != null) {
//                        in.close();
//                    }
//
//                    file.delete();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    Log.e(TAG, e.getMessage(), e);
//                    return null;
//                }
//            }
//            return new String(buffer);
//        }
//
//        return null;
//    }

}
